package com.hks.common.handle;

import com.alibaba.fastjson.JSON;
import com.hks.common.constant.StatusCode;
import com.hks.common.utils.ResponseResult;
import com.hks.common.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的 security 认证失败的异常处理
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint{
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);
    /**commence
     * 重写
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //给前端发送消息，参数一：状态码，参数二：捕获的异常信息
        ResponseResult responseResult = new ResponseResult(StatusCode.AUTHENTICATE_EX, authException.getMessage());
        String json = JSON.toJSONString(responseResult);
        logger.error("认证异常：异常信息：{}", authException.getMessage());
        WebUtils.renderString(response, json);
    }
}
